package cn.tedu.sp11.fallback;

import cn.tedu.web.util.JsonResult;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ItemFB implements FallbackProvider {
    // 返回一个 service id，针对指定的服务进行降级处理
    // 返回 "*" 或 null，对所有服务都应用这个降级类
    @Override
    public String getRoute() {
        return "item-service";
    }

    // 降级响应，返回一个封装响应数据的 response 对象
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();//状态码200
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();//状态文本
            }

            @Override
            public void close() {

            }

            //设置协议体
            @Override
            public InputStream getBody() throws IOException {
                // JsonResult {code:401, msg:调用商品服务失败, data:null}
                String json = JsonResult.err().msg("调用商品服务失败").toString();
                return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
            }

            //设置协议头
            @Override
            public HttpHeaders getHeaders() {
                // Content-Type: application/json;charset=UTF-8
                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type", "application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
